package com.cap.bts.crmdp.dealer.coupon.controller;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.cap.bts.commonfunc.common.util.UserUtil;
import com.cap.bts.crmdp.dealer.card.util.FileUtil;
import com.cap.bts.crmdp.dealer.coupon.constants.CouponConstants;
import com.cap.bts.crmdp.dealer.coupon.domain.CouponBatch;
import com.cap.bts.crmdp.dealer.coupon.domain.CouponBatchLine;
import com.cap.bts.crmdp.dealer.coupon.domain.CouponEligibility;
import com.cap.bts.crmdp.dealer.coupon.domain.Eligibility;
import com.cap.bts.crmdp.dealer.coupon.domain.EligibilityLine;
import com.cap.bts.crmdp.dealer.coupon.domain.Ticket;
import com.cap.bts.crmdp.dealer.coupon.domain.TicketLine;
import com.cap.bts.crmdp.dealer.coupon.domain.TicketLinePriceModel;
import com.cap.bts.crmdp.dealer.coupon.dto.CouponBatchDto;
import com.cap.bts.crmdp.dealer.coupon.dto.CouponBatchSubmitDto;
import com.cap.bts.crmdp.dealer.coupon.dto.CouponEligibilityDto;
import com.cap.bts.crmdp.dealer.coupon.dto.EligibilityLineDto;
import com.cap.bts.crmdp.dealer.coupon.dto.LayerViewDto;
import com.cap.bts.crmdp.dealer.coupon.dto.ProductTypesDto;
import com.cap.bts.crmdp.dealer.coupon.dto.RedeemCouponSubmitDto;
import com.cap.bts.crmdp.dealer.coupon.dto.TicKetDefineDto;
import com.cap.bts.crmdp.dealer.coupon.dto.TicketForScopeDto;
import com.cap.bts.crmdp.dealer.coupon.dto.TicketLinePriceDto;
import com.cap.bts.crmdp.dealer.coupon.service.ICouponBatchService;
import com.cap.bts.crmdp.dealer.coupon.service.ICouponEligibilityService;
import com.cap.bts.crmdp.dealer.coupon.service.ITicKetDefineService;
import com.cap.bts.crmdp.dealer.masterinfo.dto.OtherProductDto;
import com.cap.bts.crmdp.dealer.masterinfo.dto.ServiceInfoDefDto;
import com.cap.bts.crmdp.dealer.masterinfo.dto.TyreProductDto;
import com.cap.bts.crmdp.dealer.meal.constants.MealConstants;
import com.cap.bts.crmdp.dealer.meal.domain.MeallineModel;
import com.cap.bts.crmdp.dealer.meal.service.IMealManageService;
import com.cap.bts.crmdp.dealer.member.domain.CarPlateInfo;
import com.cap.bts.crmdp.dealer.member.dto.MemberQueryDto;
import com.cap.bts.crmdp.dealer.member.dto.MemberResultsDto;
import com.cap.bts.crmdp.dealer.member.service.IMaintainCarPlateService;
import com.cap.bts.framework.codemapping.constant.CodeMappingConstants;
import com.cap.bts.framework.codemapping.domain.CodeInfo;
import com.cap.bts.framework.codemapping.dto.CodeInfoDto;
import com.cap.bts.framework.codemapping.service.ICodeMapping;
import com.cap.bts.framework.common.constant.CommonConstants;
import com.cap.bts.framework.common.controller.BaseController;
import com.cap.bts.framework.common.exception.AppException;

/******************************************************************************
 * @File name   :      CouponController.java
 *
 * @Author      :      ANMA
 *
 * @Date        :      Jul 20, 2015
 *
 * @Copyright Notice: 
 * Copyright (c) 2014 DMS, Inc. All  Rights Reserved.
 * This software is published under the terms of the DMS Software
 * License version 1.0, a copy of which has been included with this
 * distribution in the LICENSE.txt file.
 * 
 * ----------------------------------------------------------------------------
 * Date                         Who         Version         Comments
 * Jul 20, 2015 7:03:02 PM    ANMA      1.0            Initial Version
 *****************************************************************************/

/**
 * 
 */
@Controller
@RequestMapping(value = "/crmdp/dealer/coupon")
public class CouponController extends BaseController {
    private static final Logger LOGGER = Logger.getLogger(CouponController.class);
    @Autowired
    ICouponBatchService couponBatchService;

    @Autowired
    ITicKetDefineService iTicKetDefineService;

    @Autowired
    IMaintainCarPlateService maintainCarPlateService;

    @Autowired
    IMealManageService iMealManageService;

    @Autowired
    ICodeMapping iCodeMapping;
    
    @Autowired
    ICouponEligibilityService couponEligibilityServiceImpl;

    static final String TICKET_PAPER = "ticketPaper";

    static final String QUERY_TICKET_NAME = "ticketName";

    static final String QUERY_TICKET_TYPE = "ticketType";

    static final String QTICKETNAME = "qticketName";

    static final String QTICKETTYPE = "qticketType";

    static final String CURRENTPAGE = "currentPage";

    static final String PAGER_CURRENTPAGE = "pager.currentPage";

    private static String TICKETNAME = "ticketName";

    private static final String JSON_STRING_UPDATE_SUCCESS = "修改成功";

    private static final String JSON_STRING_UPDATE_ERROR = "修改失败";

    private Map<String, Object> jsonResultMap = null;

    private Ticket ticket = null;

    private static final String JSON_STRING_RESULT_DELETE_SUCCESS = "删除成功";

    private static final String JSON_STRING_RESULT_DELETE_FAILD = "删除失败";

    /**
     * 优惠券活动批次管理界面
     */
    @RequestMapping(value = "/toCouponBatch")
    public String toCouponBatch(CouponBatchDto dto, Model model, HttpServletRequest request)
        throws AppException {
        CouponBatchDto cbDto = couponBatchService.getCouponBatchAllList(dto);
        model.addAttribute("dto", cbDto);
        model.addAttribute(CommonConstants.REQUEST_ATTRIBUTE_PAGER, cbDto.getPager());
        return "/coupon/couponBatchList";
    }

    /**
     * 导出优惠券页面
     * 
     * @Date : Sep 27, 2015
     * @param dto
     * @param model
     * @param request
     * @return
     * @throws AppException
     */
    @RequestMapping(value = "/toExportCouponBatchList")
    public String toExportCouponBatchList(CouponBatchDto dto, Model model,
        HttpServletRequest request) throws AppException {
        CouponBatchDto cbDto = couponBatchService.getExportCouponBatchAllList(dto);
        model.addAttribute("dto", cbDto);
        model.addAttribute(CommonConstants.REQUEST_ATTRIBUTE_PAGER, cbDto.getPager());
        return "/coupon/exportCouponBatchList";
    }

    /**
     * 查询优惠券
     * 
     * @Date : 2015年9月16日
     * @param dto
     * @param model
     * @param request
     * @return
     * @throws AppException
     */
    @RequestMapping(value = "/searchCouponBatch")
    public String searchCouponBatch(CouponBatchDto dto, Model model, HttpServletRequest request)
        throws AppException {
        CouponBatchDto cbDto = couponBatchService.getCouponBatchListwithQuery(dto);
        model.addAttribute("dto", cbDto);
        model.addAttribute(CommonConstants.REQUEST_ATTRIBUTE_PAGER, cbDto.getPager());
        return "/coupon/couponBatchList";
    }

    /**
     * 查询导出优惠券
     * 
     * @Date : 2015年9月16日
     * @param dto
     * @param model
     * @param request
     * @return
     * @throws AppException
     */
    @RequestMapping(value = "/searchExportCouponBatch")
    public String searchExportCouponBatch(CouponBatchDto dto, Model model,
        HttpServletRequest request) throws AppException {
        CouponBatchDto cbDto = couponBatchService.getExportCouponBatchListwithQuery(dto);
        model.addAttribute("dto", cbDto);
        model.addAttribute(CommonConstants.REQUEST_ATTRIBUTE_PAGER, cbDto.getPager());
        return "/coupon/exportCouponBatchList";
    }

    /**
     * 添加优惠券活动批次
     */
    @RequestMapping(value = "/toAddCouponBatch")
    public String toAddCouponBatch(CouponBatchDto dto, Model model, HttpServletRequest request)
        throws AppException {
        model.addAttribute("dto", dto);
        model.addAttribute(CommonConstants.REQUEST_ATTRIBUTE_PAGER, dto.getPager());
        return "/coupon/addCouponBatch";
    }

    /**
     * 添加优惠券活动批次处理
     */
    @RequestMapping(value = "/addCouponBatch")
    @ResponseBody
    public Boolean addCouponBatch(CouponBatch dto, Model model, HttpServletRequest request)
        throws AppException {
        if (couponBatchService.addCouponBatch(dto) != null) {
            LOGGER.info("保存成功返回值为:true");
            return true;
        }
        LOGGER.info("保存失败返回值为:false");
        return false;
    }

    /**
     * 删除优惠券活动批次处理
     */
    @RequestMapping(value = "/deleteCouponBatch")
    public String deleteCouponBatch(CouponBatchDto dto, Model model, HttpServletRequest request)
        throws AppException {
        LOGGER.info("删除活动批次id:" + dto.getSubmitDto().getId());
        couponBatchService.deleteCouponBatch(dto.getSubmitDto().getId());
        return toCouponBatch(dto, model, request);
    }

    /**
     * 追加生成优惠券
     */
    @RequestMapping(value = "/addGenerateCoupon")
    public String addGenerateCoupon(CouponBatchDto dto, Model model, HttpServletRequest request)
        throws AppException {
        couponBatchService.addGenerateCoupon(dto.getCouponBatchLine());
        // 写入批次Id
        CouponBatchSubmitDto submitDto = new CouponBatchSubmitDto();
        submitDto.setId(dto.getCouponBatchLine().getCouponBatch().getId());
        dto.setSubmitDto(submitDto);
        // 回调初始页面函数刷新页面
        return toEditCouponBatch(dto, model, request);
    }

    /**
     * 删除生成优惠券
     */
    @RequestMapping(value = "/deleteGenerateCoupon")
    public String deleteGenerateCoupon(Long delLineId, CouponBatchDto dto, Model model,
        HttpServletRequest request) throws AppException {
        couponBatchService.deleteGenerateCoupon(delLineId);
        // 写入批次Id
        CouponBatchSubmitDto submitDto = new CouponBatchSubmitDto();
        submitDto.setId(dto.getCouponBatchLine().getCouponBatch().getId());
        dto.setSubmitDto(submitDto);
        // 回调初始页面函数刷新页面
        return toEditCouponBatch(dto, model, request);
    }

    /**
     * 编辑优惠券活动批次页面
     */
    @RequestMapping(value = "/toEditCouponBatch")
    public String toEditCouponBatch(CouponBatchDto dto, Model model, HttpServletRequest request)
        throws AppException {
        LOGGER.info("编辑活动批次id:" + dto.getSubmitDto().getId());
        // 取得编辑信息
        CouponBatch cb = couponBatchService.getCouponBatchById(dto.getSubmitDto().getId());
        model.addAttribute("dto", cb);
        // 追加优惠券用的优惠券Map
        Map<Long, String> ticketMap = new HashMap<Long, String>();
        List<Ticket> ticketList = iTicKetDefineService.getCouponTicketList();
        if (ticketList != null) {
            for (Ticket t : ticketList) {
                ticketMap.put(t.getId(), t.getTicketName());
            }
        }
        // 活动批次明细list由Ticket组成:couponBatchLine
        List<CouponBatchLine> batchLineList = couponBatchService
            .getCouponBatchLineListByBatchId(dto.getSubmitDto().getId());
        for (CouponBatchLine line : batchLineList) {
            ticketMap.remove(line.getTicket().getId());
        }
        model.addAttribute("ticketMap", ticketMap);
        model.addAttribute("batchLineList", batchLineList);
        // 分页信息
        model.addAttribute(CommonConstants.REQUEST_ATTRIBUTE_PAGER, dto.getPager());
        return "/coupon/editCouponBatch";
    }

    /**
     * 导出优惠券页面
     */
    @RequestMapping(value = "/toExportCouponBatch")
    public String toExportCouponBatch(CouponBatchDto dto, Model model, HttpServletRequest request)
        throws AppException {
        LOGGER.info("导出活动批次id:" + dto.getSubmitDto().getId());
        // 取得编辑信息
        CouponBatch cb = couponBatchService.getCouponBatchById(dto.getSubmitDto().getId());
        model.addAttribute("dto", cb);
        // 追加优惠券用的优惠券ap
        Map<Long, String> ticketMap = new HashMap<Long, String>();
        List<Ticket> ticketList = iTicKetDefineService.getCouponTicketList();
        if (ticketList != null) {
            for (Ticket t : ticketList) {
                ticketMap.put(t.getId(), t.getTicketName());
            }
        }
        // 活动批次明细list由Ticket组成:couponBatchLine
        List<CouponBatchLine> batchLineList = couponBatchService
            .getCouponBatchLineListByBatchId(dto.getSubmitDto().getId());
        for (CouponBatchLine line : batchLineList) {
            ticketMap.remove(line.getTicket().getId());
        }
        model.addAttribute("ticketMap", ticketMap);
        model.addAttribute("batchLineList", batchLineList);
        // 分页信息
        model.addAttribute(CommonConstants.REQUEST_ATTRIBUTE_PAGER, dto.getPager());
        return "/coupon/exportCouponBatch";
    }

    /**
     * 会员卡导出
     * 
     * @Date : 2015-7-15
     * @param dto
     *            exportCard
     * @param model
     *            Model
     * @param request
     *            HttpServletRequest
     * @return String
     * @throws Exception
     */
    @RequestMapping(value = "/exportCoupon")
    public void exportCoupon(Long ticketId, Long batchId, Model model, HttpServletRequest request,
        HttpServletResponse response) throws AppException {
        File file = couponBatchService.generateCSVfile(batchId, ticketId);
        try {
            FileUtil.downloadZip(file, response, request);
        } catch (Exception e) {
            throw new AppException("exportCard", e);
        }
    }

    /**
     * 编辑优惠券活动批次处理
     */
    @RequestMapping(value = "/editCouponBatch")
    @ResponseBody
    public Boolean editCouponBatch(CouponBatch dto, Model model, HttpServletRequest request)
        throws AppException {
        try {
            couponBatchService.updateCouponBatch(dto);
            LOGGER.info("保存成功返回值为:true");
            return true;
        } catch (Exception e) {
            LOGGER.error("保存失败返回值为:false", e);
            return false;
        }
    }

    /**
     * 生成优惠券页面
     */
    @RequestMapping(value = "/toGenerateCoupon")
    public String toGenerateCoupon(CouponBatchDto dto, Model model, HttpServletRequest request)
        throws AppException {
        LOGGER.info("生成优惠券活动批次id:" + dto.getSubmitDto().getId());
        // 取得生成信息
        CouponBatch cb = couponBatchService.getCouponBatchById(dto.getSubmitDto().getId());
        model.addAttribute("dto", cb);

        // 活动批次明细list由Ticket组成:couponBatchLine
        List<CouponBatchLine> batchLineList = couponBatchService
            .getCouponBatchLineListByBatchId(dto.getSubmitDto().getId());
        model.addAttribute("batchLineList", batchLineList);
        // 分页信息
        model.addAttribute(CommonConstants.REQUEST_ATTRIBUTE_PAGER, dto.getPager());
        return "/coupon/generateCoupon";
    }

    /**
     * 生成优惠券活动批次处理
     */
    @ResponseBody
    @RequestMapping(value = "/generateCoupon")
    public Boolean generateCoupon(CouponBatchDto dto, Model model, HttpServletRequest request)
        throws AppException {
        boolean rtn = true;
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < dto.getLineList().size(); i++) {
            if (dto.getLineList().get(i).getCouponBatch().getId() != null
                && dto.getLineList().get(i).getTicket().getId() != null) {
                sb.append(dto.getLineList().get(i).getCouponBatch().getId().toString());
                sb.append("_");
                sb.append(dto.getLineList().get(i).getTicket().getId().toString());
                sb.append("_");
                if (dto.getLineList().get(i).getNum() != null) {
                    sb.append(dto.getLineList().get(i).getNum().toString());
                } else {
                    sb.append("0");
                }
                sb.append("_");
                sb.append(UserUtil.getCurrentUser().getId());
                sb.append(",");
                LOGGER.info(sb.toString());
            }
        }
        LOGGER.info(sb.toString());
        sb.deleteCharAt(sb.length() - 1);
        rtn = couponBatchService.generateCoupon(sb.toString());
        return rtn;
    }

    /**
     * 优惠券和提货券定义页面
     * 
     * @param dto
     * @param model
     * @param request
     * @return
     * @throws AppException
     */
    @RequestMapping(value = "toDefineTicKet")
    public String toDefineTicKet(TicKetDefineDto ticKetDefineDto, Model model,
        HttpServletRequest request) throws AppException {

        ticKetDefineDto.setTicketName(ticKetDefineDto.getQticketName());
        ticKetDefineDto.setTicketType(ticKetDefineDto.getQticketType());
        List<Ticket> ticketList = iTicKetDefineService.getTicketList(ticKetDefineDto);
        model.addAttribute(CommonConstants.REQUEST_ATTRIBUTE_PAGER, ticKetDefineDto.getPager());
        request.getSession().setAttribute(TICKET_PAPER, ticKetDefineDto.getPager());
        model.addAttribute("ticketList", ticketList);
        model.addAttribute("dto", ticKetDefineDto);
        model.addAttribute(QTICKETNAME, ticKetDefineDto.getQticketName());
        model.addAttribute(QTICKETTYPE, ticKetDefineDto.getQticketType());
        return "/coupon/defineTicket";
    }

    /**
     * 提货券定义页面
     * 
     * @param dto
     * @param model
     * @param request
     * @return
     * @throws AppException
     */
    @RequestMapping(value = "toInsertRedemption")
    public String toInsertRedemption(TicKetDefineDto dto, Model model, HttpServletRequest request)
        throws AppException {
        return "/coupon/insertRedemption";
    }

    /**
     * 优惠券定义页面
     * 
     * @param dto
     * @param model
     * @param request
     * @return
     * @throws AppException
     */
    @RequestMapping(value = "toInsertCoupon")
    public String toInsertCoupon(TicKetDefineDto dto, Model model, HttpServletRequest request)
        throws AppException {
        return "/coupon/insertCoupon";
    }

    /**
     * 提货券新增
     * 
     * @param dto
     * @param model
     * @param request
     * @return
     * @throws AppException
     */
    @RequestMapping(value = "saveRedemption")
    @ResponseBody
    public Map<String, Object> saveRedemption(TicKetDefineDto ticKetDefineDto, Model model,
        HttpServletRequest request) {
        ticKetDefineDto.setTicketType(CouponConstants.TICKET_TYPE_REDEMPTION);// 类型

        String dataStr = ticKetDefineDto.getDataStr();

        jsonResultMap = new HashMap<String, Object>();
        try {
            if (iTicKetDefineService.getTicketByTicketName(ticKetDefineDto)) {// 校验提货券是否存在
                // 新增tm_raw_ticket_def的提货券信息
                ticket = iTicKetDefineService.insertTicketInfo(ticKetDefineDto);
                if (ticket == null) {
                    jsonResultMap.put("msg", ticKetDefineDto.getTicketName()
                        + CouponConstants.REDEMPTION_ERROR_MSG);
                    jsonResultMap.put("code", false);
                    return jsonResultMap;
                }
                /** 新增tm_raw_ticket_line_def信息 */
                String[] data = dataStr.split("###");
                for (int i = 0; i < data.length; i++) {
                    String[] dataDetails = data[i].split("@#");
                    Long ticketDefId = ticket.getId();
                    String itemName = dataDetails[0];
                    Double prepayAmount = Double.valueOf(dataDetails[1]);
                    int quantity = Integer.valueOf(dataDetails[2]);

                    ticKetDefineDto.setTicketDefId(ticketDefId);
                    ticKetDefineDto.setItemName(itemName);
                    ticKetDefineDto.setPrepayAmount(prepayAmount);
                    ticKetDefineDto.setQuantity(quantity);

                    TicketLine ticketLine = iTicKetDefineService
                        .insertTicketLineInfo(ticKetDefineDto);
                    if (ticketLine == null) {
                        jsonResultMap.put("msg", ticKetDefineDto.getTicketName()
                            + CouponConstants.REDEMPTION_ERROR_MSG);
                        jsonResultMap.put("code", false);
                        return jsonResultMap;
                    }
                }
            } else {
                LOGGER.info(ticKetDefineDto.getTicketName() + "提货券已存在，不能新增");
                jsonResultMap.put("msg", ticKetDefineDto.getTicketName() + "提货券已存在，不能重复新增");
                jsonResultMap.put("code", false);
                return jsonResultMap;
            }
        } catch (AppException e) {
            LOGGER.error("新增失败", e);
            jsonResultMap.put("mag", ticKetDefineDto.getTicketName()
                + CouponConstants.REDEMPTION_ERROR_MSG);
            jsonResultMap.put("code", false);
            return jsonResultMap;
        }

        jsonResultMap.put("msg", ticKetDefineDto.getTicketName() + "提货券新增成功");
        jsonResultMap.put("code", true);
        return jsonResultMap;
    }

    /**
     * 优惠券新增
     * 
     * @param couponDataDto
     * @param model
     * @param request
     * @return
     * @throws AppException
     */
    @RequestMapping(value = "saveCoupon")
    @ResponseBody
    public Map<String, Object> saveCoupon(TicKetDefineDto ticKetDefineDto, Model model,
        HttpServletRequest request) {

        ticKetDefineDto.setTicketType(CouponConstants.TICKET_TYPE_COUPON);// 类型
        String dataStr = ticKetDefineDto.getDataStr();

        jsonResultMap = new HashMap<String, Object>();

        try {
            if (iTicKetDefineService.getTicketByTicketName(ticKetDefineDto)) {// 校验优惠券是否存在
                // 新增tm_raw_ticket_def的优惠券信息
                ticket = iTicKetDefineService.insertTicketInfo(ticKetDefineDto);
                if (ticket == null) {
                    jsonResultMap.put("msg", ticKetDefineDto.getTicketName()
                        + CouponConstants.COUPON_ERROR_MSG);
                    jsonResultMap.put("code", false);
                }
                String[] data = dataStr.split("###");
                for (int i = 0; i < data.length; i++) {
                    String[] dataDetails = data[i].split("@#");
                    Long ticketDefId = ticket.getId();
                    String itemName = dataDetails[0];
                    int quantity = Integer.valueOf(dataDetails[1]);

                    ticKetDefineDto.setTicketDefId(ticketDefId);
                    ticKetDefineDto.setItemName(itemName);
                    ticKetDefineDto.setQuantity(quantity);

                    TicketLine ticketLine = iTicKetDefineService
                        .insertTicketLineInfo(ticKetDefineDto);
                    if (ticketLine == null) {
                        jsonResultMap.put("msg", ticKetDefineDto.getTicketName()
                            + CouponConstants.COUPON_ERROR_MSG);
                        jsonResultMap.put("code", false);
                        return jsonResultMap;
                    }
                }
            } else {
                jsonResultMap.put("msg", ticKetDefineDto.getTicketName() + "优惠券已存在，不能重复新增");
                jsonResultMap.put("code", false);
                return jsonResultMap;
            }
        } catch (AppException e) {
            LOGGER.error(ticKetDefineDto.getTicketName() + CouponConstants.COUPON_ERROR_MSG, e);
            jsonResultMap.put("mag", ticKetDefineDto.getTicketName()
                + CouponConstants.COUPON_ERROR_MSG);
            jsonResultMap.put("code", false);
            return jsonResultMap;
        }
        jsonResultMap.put("msg", ticKetDefineDto.getTicketName() + "优惠券新增成功");
        jsonResultMap.put("code", true);
        return jsonResultMap;
    }

    /**
     * 优惠券和提货券查询
     * 
     * @param ticKetDefineDto
     * @param model
     * @param request
     * @return
     */
    @RequestMapping(value = "getTicketList")
    public String getTicketList(TicKetDefineDto ticKetDefineDto, Model model,
        HttpServletRequest request) throws AppException {

        ticKetDefineDto.setTicketName(ticKetDefineDto.getQticketName());
        ticKetDefineDto.setTicketType(ticKetDefineDto.getQticketType());

        List<Ticket> ticketList = iTicKetDefineService.getTicketList(ticKetDefineDto);

        model.addAttribute(CommonConstants.REQUEST_ATTRIBUTE_PAGER, ticKetDefineDto.getPager());
        model.addAttribute("ticketList", ticketList);
        model.addAttribute("dto", ticKetDefineDto);
        model.addAttribute(QTICKETNAME, ticKetDefineDto.getQticketName());
        model.addAttribute(QTICKETTYPE, ticKetDefineDto.getQticketType());
        return "/coupon/defineTicket";
    }

    /**
     * 跳转到使用优惠券页面
     * 
     * @Date : Sep 15, 2015
     * @param dto
     * @param model
     * @param request
     * @return
     * @throws AppException
     */
    @RequestMapping(value = "/toCouponRedemption")
    public String toCouponRedemption(MemberResultsDto dto, Model model, HttpServletRequest request)
        throws AppException {
        if (dto != null) {
            try {
            	String carPlate = java.net.URLDecoder.decode(dto.getCarPlate(), "UTF-8");
            	List<CarPlateInfo> carList = maintainCarPlateService.getCarPlateInfoListByCarPlateAndMemberId(carPlate, dto.getId());
            	if(carList != null && !carList.isEmpty()){
            		model.addAttribute("carId", carList.get(0).getId());
            	}
                dto.setCarPlate(carPlate);
                dto.setMemberName(java.net.URLDecoder.decode(dto.getMemberName(), "UTF-8"));
            } catch (UnsupportedEncodingException e) {
                throw new AppException("toCouponRedemption", e);
            }
        }

        model.addAttribute("dto", dto);
        MemberQueryDto memberQueryDto = (MemberQueryDto) request.getSession().getAttribute(
            "getMaintainMemberPage");
        if (memberQueryDto != null && dto != null) {
            // memberQueryDto.setIsSelected("radio"+ dto.getId()
            // +activationResultsDto.getCarPlate() +"Rad")
        }
        return "/coupon/redeemCoupon";
    }

    /**
     * 使用优惠券
     * 
     * @Date : Sep 15, 2015
     * @param dto
     * @param model
     * @param request
     * @return
     * @throws AppException
     */
    @ResponseBody
    @RequestMapping(value = "/redeemCoupon")
    public Map<String, Object> redeemCoupon(RedeemCouponSubmitDto dto, Model model,
        HttpServletRequest request) throws AppException {
        jsonResultMap = new HashMap<String, Object>();
        jsonResultMap.put("result", couponBatchService.redeemCoupon(dto));
        jsonResultMap.put("msg", dto.getErrorMsg());
        return jsonResultMap;
    }

    /**
     * 优惠券和提货券修改页面初始化
     * 
     * @param dto
     * @param model
     * @param request
     * @return
     * @throws AppException
     */
    @SuppressWarnings("rawtypes")
    @RequestMapping(value = "toEditTicket")
    public String toEditTicket(TicKetDefineDto dto, Model model, HttpServletRequest request)
        throws AppException {
        String ticketDefId = request.getParameter("ticketDefId");
        ticket = iTicKetDefineService.getTicketById(ticketDefId);

        List<TicketLine> ticketLineList = iTicKetDefineService.getTicketLineInfoList(ticketDefId);

        model.addAttribute("ticket", ticket);
        model.addAttribute(QTICKETTYPE, dto.getQticketType());
        model.addAttribute(QTICKETNAME, dto.getQticketName());
        model.addAttribute("ticketLineList", ticketLineList);
        model.addAttribute("dto", dto);
        model.addAttribute(CURRENTPAGE, request.getParameter(PAGER_CURRENTPAGE));
        model.addAttribute(CommonConstants.REQUEST_ATTRIBUTE_PAGER, dto.getPager());
        if (ticket != null) {
            if (CouponConstants.TICKET_TYPE_COUPON.equals(ticket.getTicketType())) {
            	//增加coupon使用范围 @annson 2016-01-27
            	CouponEligibilityDto couponEligibilityDto = new CouponEligibilityDto();
            	couponEligibilityDto.setTicketDefId(ticket.getId());
            	List<CouponEligibility> couponEligibilityList  = couponEligibilityServiceImpl.getCouponEligibilityList(couponEligibilityDto);
            	
            	model.addAttribute("couponEligibilityList", couponEligibilityList);
            	
            	
            	 CodeInfoDto codeInfoDto = new CodeInfoDto();
                 codeInfoDto.setType(MealConstants.CODE_TYPE_DEALERPROPERTY);

                 List<CodeInfo> codeInfoList = iCodeMapping.getCodeInfoListByParams(codeInfoDto);

                 model.addAttribute("codeInfoList", codeInfoList);
            	
            	
                return "/coupon/editCouponPage";
            } else if (CouponConstants.TICKET_TYPE_REDEMPTION.equals(ticket.getTicketType())) {
                String ticketId = Long.toString(ticket.getId());
                List<TicketLine> ticketlineList = iTicKetDefineService
                    .getTicketLineInfoList(ticketId);
                Double prepayAmount = 0.00;
                if (!ticketlineList.isEmpty()) {
                    for (Iterator iterator = ticketlineList.iterator(); iterator.hasNext();) {
                        TicketLine ticketLine = (TicketLine) iterator.next();
                        if (Long.valueOf(ticketId).equals(ticketLine.getTicketDefId())) {
                            prepayAmount = prepayAmount + ticketLine.getPrepayAmount();
                        }
                    }
                }
                model.addAttribute("prepayAmount", prepayAmount);
                return "/coupon/editRedemptionPage";
            }
        }
        return null;
    }

    /**
     * 优惠券和提货券信息修改
     * 
     * @param dto
     * @param model
     * @param request
     * @return
     * @throws AppException
     */
    @RequestMapping(value = "updateTicketInfo")
    @ResponseBody
    public Map<String, Object> updateTicketInfo(TicKetDefineDto dto, Model model,
        HttpServletRequest request) throws AppException {
        jsonResultMap = new HashMap<String, Object>();
        dto.setTicketDefId(dto.getId());
        if (iTicKetDefineService.getMealModelListByTicketId(dto)) {
            jsonResultMap.put("code", false);
            jsonResultMap.put("msg", "该笔优惠券或提货券已被有效的套餐使用，不能修改");
            return jsonResultMap;
        }
        if (iTicKetDefineService.updateTicketInfo(dto)) {
            jsonResultMap.put("code", true);
            jsonResultMap.put("msg", JSON_STRING_UPDATE_SUCCESS);
            return jsonResultMap;
        }
        jsonResultMap.put("code", false);
        jsonResultMap.put("msg", JSON_STRING_UPDATE_ERROR);
        return jsonResultMap;
    }

    /**
     * 优惠券详细信息新增页面初始化
     * 
     * @param dto
     * @param model
     * @param request
     * @return
     * @throws AppException
     */
    @RequestMapping(value = "saveCouponLineDetails")
    public String saveCouponLineDetails(TicKetDefineDto dto, Model model, HttpServletRequest request)
        throws AppException {
        model.addAttribute("ticketDefId", dto.getTicketDefId());
        model.addAttribute(QTICKETTYPE, dto.getQticketType());
        model.addAttribute(QTICKETNAME, dto.getQticketName());
        model.addAttribute(CURRENTPAGE, request.getParameter(PAGER_CURRENTPAGE));
        return "/coupon/insertCouponLine";
    }

    /**
     * 提货券详细信息新增页面初始化
     * 
     * @param dto
     * @param model
     * @param request
     * @return
     * @throws AppException
     */
    @RequestMapping(value = "saveRedemptionLineDetails")
    public String saveRedemptionLineDetails(TicKetDefineDto dto, Model model,
        HttpServletRequest request) throws AppException {
        model.addAttribute("ticketDefId", dto.getTicketDefId());
        model.addAttribute(QTICKETTYPE, dto.getQticketType());
        model.addAttribute(QTICKETNAME, dto.getQticketName());
        model.addAttribute(CURRENTPAGE, request.getParameter(PAGER_CURRENTPAGE));
        return "/coupon/insertRedemptionLine";
    }

    /**
     * 优惠券和提货券详细信息新增
     * 
     * @param dto
     * @param model
     * @param request
     * @return
     * @throws AppException
     */
    @RequestMapping(value = "insertTiketLineInfo")
    @ResponseBody
    public Map<String, Object> insertTiketLineInfo(TicKetDefineDto dto, Model model,
        HttpServletRequest request) throws AppException {
        jsonResultMap = new HashMap<String, Object>();
        TicketLine ticketLine = iTicKetDefineService.insertTicketLineInfo(dto);
        if (ticketLine != null) {
            jsonResultMap.put("code", true);
            jsonResultMap.put("msg", "新增成功");
            return jsonResultMap;
        }
        jsonResultMap.put("code", false);
        jsonResultMap.put("msg", "新增失败");
        return jsonResultMap;
    }

    /**
     * 优惠券详细信息修改页面初始化
     * 
     * @param dto
     * @param model
     * @param request
     * @return
     * @throws AppException
     */
    @RequestMapping(value = "toCouponLinePage")
    public String toCouponLinePage(TicKetDefineDto dto, Model model, HttpServletRequest request)
        throws AppException {

        String id = request.getParameter("id");
        TicketLine ticketLine = iTicKetDefineService.getTicketLineInfoById(Long.valueOf(id));
        model.addAttribute("ticketLine", ticketLine);
        model.addAttribute(QTICKETTYPE, dto.getQticketType());
        model.addAttribute(QTICKETNAME, dto.getTicketName());
        model.addAttribute(CURRENTPAGE, request.getParameter(PAGER_CURRENTPAGE));
        return "/coupon/editCouponLine";
    }

    /**
     * 提货券详细信息修改页面初始化
     * 
     * @param dto
     * @param model
     * @param request
     * @return
     * @throws AppException
     */
    @RequestMapping(value = "toRedemptionLinePage")
    public String toRedemptionLinePage(TicKetDefineDto dto, Model model, HttpServletRequest request)
        throws AppException {

        TicketLine ticketLine = iTicKetDefineService.getTicketLineInfoById(dto.getId());
        model.addAttribute(QTICKETTYPE, dto.getQticketType());
        model.addAttribute(QTICKETNAME, dto.getTicketName());
        model.addAttribute(CURRENTPAGE, request.getParameter(PAGER_CURRENTPAGE));
        model.addAttribute("ticketLine", ticketLine);
        return "/coupon/editRedemptionLine";

    }

    /**
     * 优惠券和提货券详细信息修改
     * 
     * @param dto
     * @param model
     * @param request
     * @return
     * @throws AppException
     */
    @RequestMapping(value = "updateTiketLineInfo")
    @ResponseBody
    public Map<String, Object> updateTiketLineInfo(TicKetDefineDto dto, Model model,
        HttpServletRequest request) throws AppException {
        jsonResultMap = new HashMap<String, Object>();
        Long ticketDefId = dto.getTicketDefId();

        ticket = iTicKetDefineService.getTicketById(Long.toString(ticketDefId));
        dto.setTicketType(ticket.getTicketType());

        if (iTicKetDefineService.updateTiketLineInfo(dto)) {
            jsonResultMap.put("code", true);
            jsonResultMap.put("msg", JSON_STRING_UPDATE_SUCCESS);
            return jsonResultMap;
        }
        jsonResultMap.put("code", false);
        jsonResultMap.put("msg", JSON_STRING_UPDATE_ERROR);
        return jsonResultMap;
    }

    /**
     * 优惠券和提货券详细信息删除
     * 
     * @param dto
     * @param model
     * @param request
     * @return
     * @throws AppException
     */
    @RequestMapping(value = "removeTiketLineInfo")
    @ResponseBody
    public Map<String, Object> removeTiketLineInfo(TicKetDefineDto dto, Model model,
        HttpServletRequest request) throws AppException {

        String ticketDefId = request.getParameter("ticketDefId");
        jsonResultMap = new HashMap<String, Object>();
        List<TicketLine> ticketLineList = iTicKetDefineService.getTicketLineInfoList(ticketDefId);
        if (!ticketLineList.isEmpty() && ticketLineList.size() == 1) {
            jsonResultMap.put("code", false);
            jsonResultMap.put("msg", "无法删除，必须要保留一行数据");
            return jsonResultMap;
        }

        if (iTicKetDefineService.removeTiketLineInfo(dto)) {
            jsonResultMap.put("code", true);
            jsonResultMap.put("msg", JSON_STRING_RESULT_DELETE_SUCCESS);
            return jsonResultMap;
        }
        jsonResultMap.put("code", false);
        jsonResultMap.put("msg", JSON_STRING_RESULT_DELETE_FAILD);
        return jsonResultMap;
    }

    /**
     * 根据ID删除优惠券、提货券信息以及其的详细信息
     * 
     * @param dto
     * @param model
     * @param request
     * @return
     * @throws AppException
     */
    @RequestMapping(value = "removeTicketInfoById")
    @ResponseBody
    public Map<String, Object> removeTicketInfoById(TicKetDefineDto dto, Model model,
        HttpServletRequest request) throws AppException {
        String id = request.getParameter("id");

        model.addAttribute(TICKETNAME, dto.getTicketName());
        model.addAttribute("ticketType", dto.getTicketType());
        if (id != null && !"".equals(id)) {
            jsonResultMap = new HashMap<String, Object>();
            ticket = iTicKetDefineService.getTicketById(Long.toString(dto.getId()));
            if (ticket != null) {
                List<MeallineModel> meallineList = iMealManageService
                    .getMeallineListByTicketDefId(dto.getId());
                if (!meallineList.isEmpty()) {
                    jsonResultMap.put("code", false);
                    jsonResultMap.put("msg", ticket.getTicketName() + " 已被使用，不能删除");
                    return jsonResultMap;
                }

                if (iTicKetDefineService.removeTicketInfo(ticket.getId())) {
                    jsonResultMap.put("code", true);
                    jsonResultMap.put("msg", JSON_STRING_RESULT_DELETE_SUCCESS);
                    return jsonResultMap;
                }
            } else {
                jsonResultMap.put("code", false);
                jsonResultMap.put("msg", "该笔数据异常,请联系管理员");
                return jsonResultMap;
            }
        }
        jsonResultMap.put("code", false);
        jsonResultMap.put("msg", JSON_STRING_RESULT_DELETE_FAILD);
        return jsonResultMap;
    }

    /**
     * @Date : 2015年10月20日
     * @param model
     * @param request
     * @return
     * @throws AppException
     */
    @RequestMapping(value = "/toScopeOfTicket")
    public String toScopeOfTicket(TicketForScopeDto ticketForScopeDto, Model model,
        HttpServletRequest request) throws AppException {
        Long ticketLineId = null;
        if (ticketForScopeDto != null) {
            ticketLineId = ticketForScopeDto.getTicketLineId();
            if (ticketLineId != null) {
                List<Eligibility> eligibilityList = iTicKetDefineService
                    .getEligibilityByTicketLineId(ticketLineId);
                //头表
                if (eligibilityList != null && !eligibilityList.isEmpty()) {
                    List<EligibilityLineDto> eligibilityLineDtoList = new ArrayList<EligibilityLineDto>();
                    Eligibility eligibility = eligibilityList.get(0);
                    if(eligibility != null){
                        List<EligibilityLine> eligibilityLines = iTicKetDefineService.getEligibilityLineByEligibilityId(eligibility.getId());
                        if(eligibilityLines != null && !eligibilityLines.isEmpty()){
                            for(int i=0; i<eligibilityLines.size(); i++){
                                EligibilityLineDto eligibilityLineDto = new EligibilityLineDto();
                                eligibilityLineDto.setId(eligibilityLines.get(i).getId());
                                eligibilityLineDto.setEligibilityId(eligibilityLines.get(i).getEligibilityId());
                                eligibilityLineDto.setAttrName(eligibilityLines.get(i).getAttrName());
                                eligibilityLineDto.setAttrValue(eligibilityLines.get(i).getAttrValue());
                                eligibilityLineDto.setOperator(eligibilityLines.get(i).getOperator());
                                eligibilityLineDtoList.add(eligibilityLineDto);
                            }
                        }
                    }
                    model.addAttribute("eligibility", eligibility);
                    model.addAttribute("eligibilityLineDtoList", eligibilityLineDtoList);
                    model.addAttribute("ticketLineId", ticketLineId);
                    return "/coupon/scopeOfTicket";
                }
                model.addAttribute("ticketLineId", ticketLineId);
            }
        }
        return "/coupon/scopeOfTicketForInsert";
    }

    /**
     * 适用范围---定义值
     * 
     * @Date : 2015年10月22日
     * @param model
     * @param request
     * @return
     * @throws AppException
     */
    @RequestMapping(value = "/toEditPropertyLineValue")
    public String toEditPropertyLineValue(Model model, HttpServletRequest request)
        throws AppException {
        return "/coupon/propertylinevalue";
    }

    /**
     * @Date : 2015年10月21日
     * @param productType
     * @param model
     * @param request
     * @return
     * @throws AppException
     */
    @RequestMapping(value = "/showPropertyOfProduct")
    @ResponseBody
    public Map<String, Object> showPropertyOfProduct(ProductTypesDto productType, Model model,
        HttpServletRequest request) throws AppException {
        if (productType != null) {
            String type = productType.getProductType();
            String code = "";
            String productCode = null;
            List<String> codeList = null;
            if(type != null && !"".equals(type)){
                if(type.equals(CouponConstants.MAINGROUP)){
                    code = CouponConstants.MAIN_GROUP;
                }else if(type.equals(CouponConstants.SUBGROUP)){
                    code = CouponConstants.SUB_GROUP;
                }else if(type.equals(CouponConstants.POSITIONGROUP)){
                    code = CouponConstants.POSITION_GROUP;
                }
            }
            List<String> typeValueList = iTicKetDefineService.getCodeListFromTable(CouponConstants.TM_MARS_POSITION_GROUP);
            if(typeValueList != null && !typeValueList.isEmpty()){
                for(int i=0; i<typeValueList.size(); i++){
                    if(code.equals(typeValueList.get(i))){
                        productCode = code;
                        break;
                    }
                }
            }
            if(productCode != null){
                codeList = iTicKetDefineService.getTypeValueList(productCode);
            }
            Map<String, Object> map = new HashMap<String, Object>();
            if (codeList != null && !codeList.isEmpty()) {
                map.put("codeList", codeList);
            } else {
                map.put("codeList", null);
            }
            return map;
        }
        return null;
    }
    
    @RequestMapping(value = "/showPropertyOfProductTypeValue")
    @ResponseBody
    public Map<String, Object> showPropertyOfProductTypeValue(String productType, Model model,
        String productTypeValue) throws AppException {
        String productTypeStr=productType;
        if (productTypeStr != null && productTypeValue != null) {
            if(CouponConstants.POSITIONGROUP.equals(productTypeStr)){
                List<CodeInfo> codeInfoList = iTicKetDefineService.getCodeValue(productTypeValue);
                Map<String, Object> map = new HashMap<String, Object>();
                if(codeInfoList != null && !codeInfoList.isEmpty()){
                    map.put("codeInfoList", codeInfoList);
                }else{
                    map.put("codeInfoList", null);
                }
                return map;
            }else if(CouponConstants.SUBGROUP.equals(productTypeStr) ||
                CouponConstants.MAINGROUP.equals(productTypeStr)){
                if(CouponConstants.MAINGROUP.equals(productTypeStr)){
                    productTypeStr = CouponConstants.MAIN_GROUP;
                }else if(CouponConstants.SUBGROUP.equals(productTypeStr)){
                    productTypeStr = CouponConstants.SUB_GROUP;
                }
                List<String> positionGroupList = iTicKetDefineService.getPositionGroupList(productTypeStr, productTypeValue);
                List<String> codeValueList = iTicKetDefineService.getCodeValueByCodeTypeList(positionGroupList);
                Map<String, Object> map = new HashMap<String, Object>();
                if(codeValueList != null && !codeValueList.isEmpty()){
                    map.put("codeValueList", codeValueList);
                }else{
                    map.put("codeValueList", null);
                }
                return map;
            }
        }
        return null;
    }

    @RequestMapping(value = "/showDescriptionOfProperty")
    @ResponseBody
    public Map<String, Object> showDescriptionOfProperty(ProductTypesDto productType, Model model,
        HttpServletRequest request) throws AppException {
        String description = null;
        if (productType != null) {
            description = iTicKetDefineService.getDescriptionOfProduct(productType.getCodeValue());
        }
        Map<String, Object> map = new HashMap<String, Object>();
        if (description != null) {
            map.put("description", description);
        } else {
            map.put("description", null);
        }
        return map;
    }

    @RequestMapping(value = "/showViewOfTicket")
    @ResponseBody
    public LayerViewDto showViewOfTicket(Model model, HttpServletRequest request)
        throws AppException {
        String[] ticketLineIdList = request.getParameterValues("ticketLineId");
        String[] partTypeList = request.getParameterValues("partType");
        String[] partTypeValueList = request.getParameterValues("partTypeValue");
        String[] attrNameList = request.getParameterValues("attrName");
        String[] operatorList = request.getParameterValues("operator");
        String[] attrValueList = request.getParameterValues("attrValue");
        StringBuilder sql = new StringBuilder();
        StringBuilder select = new StringBuilder();
        StringBuilder where = new StringBuilder();
        StringBuilder from = new StringBuilder();
        LayerViewDto layerViewDto = new LayerViewDto();
        //转化attrNameList
        if(partTypeValueList != null && partTypeValueList.length > 0){
        	String type = partTypeValueList[0];
            select.append("select");
            where.append(" where");
            from.append(" from");
            //获取codeValue
            if(partTypeList != null && partTypeList.length > 0){
                String attrType = partTypeList[0];
                if(attrType != null && !"".equals(attrType)){
                    if(attrType.equals(CouponConstants.MAINGROUP)){
                        attrType = CouponConstants.MAIN_GROUP;
                    }else if(attrType.equals(CouponConstants.SUBGROUP)){
                        attrType = CouponConstants.SUB_GROUP;
                    }else if(attrType.equals(CouponConstants.POSITIONGROUP)){
                        attrType = CouponConstants.POSITION_GROUP;
                    }
                    if(type != null && !"---请选择---".equals(type)){
                        List<String> positionGroupList = iTicKetDefineService.getPositionGroupList(attrType, type);
                        if(positionGroupList != null && !positionGroupList.isEmpty()){
                            //判断是否只有头表
                            boolean allEmpty = true;
                            if(attrNameList != null && attrNameList.length > 0){
	                            for(int i=0; i<attrNameList.length; i++){
	                                if(!"---请选择---".equals(attrNameList[i])){
	                                    allEmpty = false;
	                                }
	                            }
                            }
                            //只有头表
                            if(allEmpty){
                                if(attrType != null){
                                    String table = null;
                                    if(attrType.equals(CouponConstants.POSITION_GROUP)){
                                        table = iTicKetDefineService.getParentCodeByCodeType(partTypeValueList[0]);
                                    }else{
                                        for(int i=0;i<positionGroupList.size(); i++){
                                            String str = iTicKetDefineService.getParentCodeByCodeType(positionGroupList.get(i));
                                            if(str == null){
                                                continue;
                                            }else{
                                                table = str;
                                            }
                                        }
                                    }
                                    if(table != null){
                                        select.append(" *");
                                        from.append(" " + table);
                                        where.append(" " + attrType + " = '" + partTypeValueList[0] + "'");
                                        if(CodeMappingConstants.TM_SERVICE_DEF.equals(table)){
                                            layerViewDto.setType(CodeMappingConstants.TYPE_SERVICE);
                                        }else if(CodeMappingConstants.TM_TYRE_PRODUCT.equals(table)){
                                            layerViewDto.setType(CodeMappingConstants.TYPE_TYRE);
                                        }
                                        sql.append(select);
                                        sql.append(from);
                                        sql.append(where);
                                        String sqlStr = sql.toString().replace("\'", "\"");
                                        iTicKetDefineService.saveSql(sqlStr);
                                        Long id = iTicKetDefineService.querySql(sqlStr);
                                        layerViewDto.setSqlId(id);
                                    }
                                }
                            }else{
                                //头表行表都有
                                if (operatorList != null && ticketLineIdList != null
                                    && !"undefined".equals(ticketLineIdList[0])) {
                                    String tableName = null;
                                    if(attrType.equals(CouponConstants.POSITION_GROUP)){
                                        tableName = iTicKetDefineService.getParentCodeByCodeType(partTypeValueList[0]);
                                    }else{
                                        for(int i=0;i<positionGroupList.size(); i++){
                                            String str = iTicKetDefineService.getParentCodeByCodeType(positionGroupList.get(i));
                                            if(str == null){
                                                continue;
                                            }else{
                                                tableName = str;
                                            }
                                        }
                                    }
                                    if(tableName != null){
                                    	if(attrNameList != null && attrNameList.length > 0){
                                    		String[] attrNameListForWeCare =  new String[attrNameList.length];
                                    		if(type != null && !"---请选择---".equals(type)){
                                    			for(int i=0; i<attrNameList.length; i++){
                                    				List<String> list = iTicKetDefineService.getCodeByValue(attrNameList[i]);
                                    				if(list != null && !list.isEmpty()){
                                    					attrNameListForWeCare[i] = list.get(0);
                                    				}
                                    			}
                                    		}
                                    		if (CodeMappingConstants.TM_SERVICE_DEF.equals(tableName) && attrNameListForWeCare != null
                                    				&& attrNameListForWeCare.length > 0) {
                                    			select.append(" *");
                                    			from.append(" " + CodeMappingConstants.TM_SERVICE_DEF);
                                    			where.append(" " + attrType + " = '" + partTypeValueList[0] + "' and ");
                                    			where = iTicKetDefineService.showViewSQL(attrNameListForWeCare, operatorList, attrValueList, where);
                                    			layerViewDto.setType(CodeMappingConstants.TYPE_SERVICE);
                                    			
                                    		} else if (CodeMappingConstants.TM_TYRE_PRODUCT.equals(tableName) && attrNameListForWeCare != null
                                    				&& attrNameListForWeCare.length > 0) {
                                    			select.append(" *");
                                    			from.append(" " + CodeMappingConstants.TM_TYRE_PRODUCT);
                                    			where.append(" " + attrType + " = '" + partTypeValueList[0] + "' and ");
                                    			where = iTicKetDefineService.showViewSQL(attrNameListForWeCare, operatorList, attrValueList, where);
                                    			layerViewDto.setType(CodeMappingConstants.TYPE_TYRE);
                                    			
                                    		} else {
                                    			if (attrNameListForWeCare != null && attrNameListForWeCare.length > 0) {
                                    				select.append(" *");
                                    				from.append(" " + CodeMappingConstants.TM_OTHER_PRODUCT);
                                    				where.append(" " + attrType + " = '" + partTypeValueList[0] + "' and ");
                                    				where = iTicKetDefineService.showViewSQL(attrNameListForWeCare, operatorList, attrValueList, where);
                                    			}
                                    		}
                                    		sql.append(select);
                                    		sql.append(from);
                                    		sql.append(where);
                                    	}
                                    }
                                    String sqlStr = sql.toString().replace("\'", "\"");
                                    iTicKetDefineService.saveSql(sqlStr);
                                    Long id = iTicKetDefineService.querySql(sqlStr);
                                    layerViewDto.setSqlId(id);
                                }
                            }
                        }
                    }
                }
            }
            
        }
        return layerViewDto;
    }
    
        
    

    @RequestMapping(value = "/showViewForLayer")
    public String showViewForLayer(LayerViewDto layerViewDto, Model model,
        HttpServletRequest request) throws AppException {
        if (layerViewDto != null) {
            String sqlStr = iTicKetDefineService.querySqlById(layerViewDto.getSqlId());
            String sql = sqlStr.replace("\"", "\'");
            if (layerViewDto.getType().equals(CodeMappingConstants.TYPE_TYRE)) {
                List<TyreProductDto> tyreProductDtoList = iTicKetDefineService.getViewForTyre(sql);
                model.addAttribute("resultList", tyreProductDtoList);
                model.addAttribute("result", CodeMappingConstants.TYRE_OR_OTHER_PRODUCT);
                model.addAttribute("sql", sql);
            } else if (layerViewDto.getType().equals(CodeMappingConstants.TYPE_SERVICE)) {
                List<ServiceInfoDefDto> serviceInfoDefList = iTicKetDefineService
                    .getViewForService(sql);
                model.addAttribute("ServiceInfoDefList", serviceInfoDefList);
                model.addAttribute("result", CodeMappingConstants.SERVICE);
                model.addAttribute("sql", sql);
            } else {
                List<OtherProductDto> otherProductDtoList = iTicKetDefineService
                    .getViewForOtherProduct(sql);
                model.addAttribute("resultList", otherProductDtoList);
                model.addAttribute("result", CodeMappingConstants.TYRE_OR_OTHER_PRODUCT);
                model.addAttribute("sql", sql);
            }
            iTicKetDefineService.deleteSqlById(layerViewDto.getSqlId());
        }
        return "/coupon/viewOfTicket";
    }

    @RequestMapping(value = "/saveScopeOfTicket")
    @ResponseBody
    public boolean saveScopeOfTicket(Model model, HttpServletRequest request) throws AppException {
        String[] ticketLineIdList = request.getParameterValues("ticketLineId");
        String[] partTypeList = request.getParameterValues("partType");
        String[] partTypeValueList = request.getParameterValues("partTypeValue");
        String[] checkboxList = request.getParameterValues("checkbox");
        String[] attrNameList = request.getParameterValues("attrName");
        String[] operatorList = request.getParameterValues("operator");
        String[] attrValueList = request.getParameterValues("attrValue");
        String[] eligibilityLineIdList = request.getParameterValues("id");
        if(ticketLineIdList.length > 0 && !"undefined".equals(ticketLineIdList[0])
            && partTypeList.length > 0 && !"---请选择---".equals( partTypeList[0])){
            //存头表
            Long ticketLineId = null;
            if (ticketLineIdList[0] != null) {
                ticketLineId = Long.parseLong(ticketLineIdList[0]);
            }
            if(partTypeValueList.length > 0 && !"---请选择---".equals( partTypeValueList[0])){
                Long eId = iTicKetDefineService.isExitsRowInEligibility(ticketLineId);
                if (eId != null) {
                    // 更新
                    if(checkboxList != null){
                        iTicKetDefineService.changeRowInEligibility(Long.parseLong(ticketLineIdList[0]),partTypeList[0],partTypeValueList[0],checkboxList[0],eId);
                    }else {
                        iTicKetDefineService.changeRowInEligibility(Long.parseLong(ticketLineIdList[0]),partTypeList[0],partTypeValueList[0],"N",eId);
                    }
                }else{
                    //保存
                    if(checkboxList != null){
                        iTicKetDefineService.saveRowInEligibility(Long.parseLong(ticketLineIdList[0]), partTypeList[0], partTypeValueList[0], checkboxList[0]);
                    }else{
                        iTicKetDefineService.saveRowInEligibility(Long.parseLong(ticketLineIdList[0]), partTypeList[0], partTypeValueList[0], "N");
                    }
                }
                
                //存行表
                if(operatorList != null && operatorList.length>0){
                    List<Eligibility> list = iTicKetDefineService.getEligibilityByTicketLineId(ticketLineId);
                    if(list != null && !list.isEmpty()){
                        Long eligibilityId = list.get(0).getId();
                        if (eligibilityLineIdList != null && eligibilityLineIdList.length > 0) {
                            // 删除
                            List<EligibilityLine> eligibilityLineList = iTicKetDefineService.getEligibilityLineByEligibilityId(eligibilityId);
                            if (eligibilityLineList != null && !eligibilityLineList.isEmpty()) {
                                for (int i = 0; i < eligibilityLineList.size(); i++) {
                                    boolean exits = false;
                                    for (int f = 0; f < eligibilityLineIdList.length; f++) {
                                        if (eligibilityLineList.get(i).getId() == Long
                                            .parseLong(eligibilityLineIdList[f])) {
                                            exits = true;
                                        }
                                    }
                                    if (!exits) {
                                        iTicKetDefineService.removeRow(eligibilityLineList.get(i).getId());
                                    }
                                    if("---请选择---".equals(attrNameList[i])){
                                        iTicKetDefineService.removeRow(eligibilityLineList.get(i).getId());
                                    }
                                }
                            }
                            
                            for (int i = 0; i < eligibilityLineIdList.length; i++) {
                                boolean isExitsInEligibilityLine = iTicKetDefineService.isExitsRow(Long.parseLong(eligibilityLineIdList[i]));
                                if (isExitsInEligibilityLine) {
                                    // 更新
                                    iTicKetDefineService.changeRow(eligibilityId,attrNameList[i],
                                        operatorList[i], attrValueList[i],eligibilityLineIdList[i]);
                                } else {
                                    // 新增
                                    iTicKetDefineService.saveRow(eligibilityId,attrNameList[i],
                                        operatorList[i], attrValueList[i]);
                                }
                            }
                            if (eligibilityLineIdList.length < operatorList.length) {
                                for (int i = eligibilityLineIdList.length; i < operatorList.length; i++) {
                                    if (!"---请选择---".equals(attrNameList[i])) {
                                        iTicKetDefineService.saveRow(eligibilityId,attrNameList[i],
                                            operatorList[i], attrValueList[i]);
                                    }
                                }
                            }
                            return true;
                        } else {
                            if(operatorList.length>0){
                                for (int i = 0; i < operatorList.length; i++) {
                                    if (!"---请选择---".equals(attrNameList[i])) {
                                        iTicKetDefineService.saveRow(eligibilityId,attrNameList[i],
                                            operatorList[i], attrValueList[i]);
                                    }
                                }
                                return true;
                            }
                        }
                    }
                }else{
                    List<Eligibility> list = iTicKetDefineService.getEligibilityByTicketLineId(ticketLineId);
                    if(list != null && !list.isEmpty()){
                        Long eligibilityId = list.get(0).getId();
                        List<EligibilityLine> eligibilityLineList = iTicKetDefineService.getEligibilityLineByEligibilityId(eligibilityId);
                        if(eligibilityLineList != null && !eligibilityLineList.isEmpty()){
                            iTicKetDefineService.removeRowByEligibilityId(eligibilityId);
                        }
                        return true;
                    }
                }
            }
        }
        return false;
    }

    /**
     * 价目表管理初始化页面
     * 
     * @param dto
     * @param model
     * @param request
     * @return
     * @throws AppException
     */
    @RequestMapping(value = "toTicketLinePricePage")
    public String toTicketLinePricePage(TicketLinePriceDto dto, Model model,
        HttpServletRequest request) throws AppException {
        model.addAttribute("ticketLineId", dto.getTicketLineId());

        CodeInfoDto codeInfoDto = new CodeInfoDto();
        codeInfoDto.setType(MealConstants.CODE_TYPE_DEALERPROPERTY);

        List<CodeInfo> codeInfoList = iCodeMapping.getCodeInfoListByParams(codeInfoDto);

        model.addAttribute("codeInfoList", codeInfoList);

        TicketLinePriceDto ticketLinePriceDto = new TicketLinePriceDto();
        ticketLinePriceDto.setTicketLineId(dto.getTicketLineId());
        List<TicketLinePriceModel> ticketLinePriceList = iTicKetDefineService
            .getMealPriceListByPackageId(ticketLinePriceDto);

        model.addAttribute("codeType", MealConstants.CODE_TYPE_DEALERPROPERTY);
        model.addAttribute("mealPriceList", ticketLinePriceList);
        model.addAttribute("ticketDefId", request.getParameter("ticketDefId"));
        model.addAttribute(QTICKETTYPE, request.getParameter(QTICKETTYPE));
        model.addAttribute(QTICKETNAME, request.getParameter(QTICKETNAME));
        model.addAttribute(CURRENTPAGE, request.getParameter(PAGER_CURRENTPAGE));
        return "/coupon/ticketLinePrice";
    }

    /**
     * 价目表新增
     * 
     * @param dto
     * @param model
     * @param request
     * @return
     * @throws AppException
     */
    @RequestMapping(value = "saveTicketLinePriceinfo")
    @ResponseBody
    public Map<String, Object> saveTicketLinePriceinfo(TicketLinePriceDto dto, Model model,
        HttpServletRequest request) throws AppException {
        Map<String, Object> map = new HashMap<String, Object>();

        TicketLinePriceDto ticketLinePriceDto = null;
        String priceStr = dto.getPriceStr();
        if (priceStr != null && !"".equals(priceStr)) {
            String[] data = priceStr.split("###");
            for (int i = 0; i < data.length; i++) {
                String[] pStrings = data[i].split("@#");
                String code = pStrings[0];
                String value = pStrings[1];
                ticketLinePriceDto = new TicketLinePriceDto();
                ticketLinePriceDto.setCode(code);
                ticketLinePriceDto.setValue(value);
                ticketLinePriceDto.setTicketLineId(dto.getTicketLineId());
                // 检查该价目表是否已经新增
                TicketLinePriceModel ticketLinePriceModel = iTicKetDefineService
                    .getMealPriceInfo(ticketLinePriceDto);
                if (ticketLinePriceModel != null) {
                    map.put("code", false);
                    map.put("msg", ticketLinePriceModel.getValue() + "的价目表已存在");
                    return map;
                }
            }
        }

        if (iTicKetDefineService.saveMealPriceinfo(dto)) {
            map.put("code", true);
            map.put("msg", "价目表新增成功");
            return map;
        }
        map.put("code", false);
        map.put("msg", "价目表新增失败");
        return map;
    }

    /**
     * 价目表删除
     * 
     * @param dto
     * @param model
     * @param request
     * @return
     * @throws AppException
     */
    @RequestMapping(value = "removeTicketLinePrice")
    @ResponseBody
    public Map<String, Object> removeTicketLinePrice(TicketLinePriceDto dto, Model model,
        HttpServletRequest request) throws AppException {
        Map<String, Object> map = new HashMap<String, Object>();
        if (iTicKetDefineService.removeMealPriceById(dto.getId())) {
            map.put("code", true);
            map.put("msg", "价目表删除成功");
            return map;
        }
        map.put("code", false);
        map.put("msg", "价目表删除失败");
        return map;
    }

    /**
     * 价目表修改页面初始化
     * 
     * @param dto
     * @param model
     * @param request
     * @return
     * @throws AppException
     */
    @RequestMapping(value = "toEditTicketLinePricePage")
    public String toEditTicketLinePricePage(TicketLinePriceDto dto, Model model,
        HttpServletRequest request) throws AppException {

        CodeInfoDto codeInfoDto = new CodeInfoDto();
        codeInfoDto.setType(MealConstants.CODE_TYPE_DEALERPROPERTY);

        List<CodeInfo> codeInfoList = iCodeMapping.getCodeInfoListByParams(codeInfoDto);

        TicketLinePriceModel ticketLinePriceModel = iTicKetDefineService.getMealPriceInfo(dto);

        CodeInfo codeInfo = iCodeMapping.getCodeInfoByCode(ticketLinePriceModel.getCode());

        model.addAttribute("codeValue", codeInfo.getValue());
        model.addAttribute("codeInfoList", codeInfoList);
        model.addAttribute("mealPriceModel", ticketLinePriceModel);

        model.addAttribute("id", dto.getId());
        model.addAttribute("ticketLineId", dto.getTicketLineId());
        model.addAttribute("ticketDefId", request.getParameter("ticketDefId"));

        model.addAttribute(QTICKETTYPE, request.getParameter(QTICKETTYPE));
        model.addAttribute(QTICKETNAME, request.getParameter(QTICKETNAME));
        model.addAttribute(CURRENTPAGE, request.getParameter(PAGER_CURRENTPAGE));

        return "/coupon/editTicketLinePrice";
    }

    /**
     * 价目表修改
     * 
     * @param dto
     * @param model
     * @param request
     * @return
     * @throws AppException
     */
    @RequestMapping(value = "updateTicketLinePrice")
    @ResponseBody
    public Map<String, Object> updateTicketLinePrice(TicketLinePriceDto dto, Model model,
        HttpServletRequest request) throws AppException {
        Map<String, Object> map = new HashMap<String, Object>();

        TicketLinePriceDto ticketLinePriceDto = new TicketLinePriceDto();
        ticketLinePriceDto.setCode(dto.getCode());
        ticketLinePriceDto.setValue(dto.getValue());
        ticketLinePriceDto.setTicketLineId(dto.getTicketLineId());
        if (iTicKetDefineService.updateMealPriceInfo(dto)) {
            map.put("code", true);
            map.put("msg", "价目表修改成功");
            return map;
        }
        map.put("code", false);
        map.put("msg", "价目表修改失败");
        return map;
    }

    /**
     * 根据优惠券或提货券ID查询是否套餐是否有效
     * 
     * @param ticKetDefineDto
     * @return
     * @throws AppException
     */
    @RequestMapping(value = "checkPackageByTicketDefId")
    @ResponseBody
    public Map<String, Object> checkPackageByTicketDefId(TicKetDefineDto ticKetDefineDto)
        throws AppException {

        Map<String, Object> jsonMap = new HashMap<String, Object>();
        if (iTicKetDefineService.getMealModelListByTicketId(ticKetDefineDto)) {
            jsonMap.put("code", false);
            jsonMap.put("msg", "该笔优惠券或提货券已被有效的套餐使用，不能修改其行信息");
            return jsonMap;
        }
        jsonMap.put("code", true);
        return jsonMap;
    }

    @RequestMapping(value = "/toUpdateTicketPriceOfDealer")
    public String toUpdateTicketPriceOfDealer() throws AppException {
        return "/coupon/updateTicketPrice";
    }

    @RequestMapping(value = "/saveTicketPriceOfDealer")
    @ResponseBody
    public boolean saveTicketPriceOfDealer() throws AppException {
        return iTicKetDefineService.saveTicketPriceOfDealer();
    }
    
    @RequestMapping(value = "/removeAll")
    @ResponseBody
    public boolean removeAll(String ticketLineId, Model model,HttpServletRequest request) throws AppException {
        if(ticketLineId != null && !"".equals(ticketLineId)){
            List<Eligibility> eligibilityList = iTicKetDefineService.getEligibilityByTicketLineId(Long.parseLong(ticketLineId));
            if(eligibilityList != null && !eligibilityList.isEmpty()){
                Eligibility eligibility = eligibilityList.get(0);
                List<EligibilityLine> eligibilityLineList = iTicKetDefineService.getEligibilityLineByEligibilityId(eligibility.getId());
                if(eligibilityLineList != null && !eligibilityLineList.isEmpty()){
                    iTicKetDefineService.removeRowByEligibilityId(eligibility.getId());
                }
                iTicKetDefineService.removeEligibilityByTicketLineId(Long.parseLong(ticketLineId));
            }
            return true;
        }
        return false;
    }

}
